/**
 * $Id$ Copyright 2009-2012 Oak Pacific Interactive. All rights reserved.
 */
package com.shuqi.activity.adapter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.shuqi.activity.viewport.CircleProgressBarView;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.Log4an;
import com.shuqi.controller.R;
import com.shuqi.database.model.TxtDownload;
import com.shuqi.model.manager.FreeBookDownloadManager.DownConstant;

/**
 * 
 * 
 * @author <a href="mailto:">yaozhen</a>
 * @version 2014-2-17下午7:32:45
 */
public class BookDownloadAdapter extends BaseAdapter {

    public static final String TAG = "BookDownloadAdapter";

    private List<TxtDownload> mList;

    private SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");

    private Date mDate = new Date();

    private HashMap<BookDownHolder, String> mCacheUIMap =
            new HashMap<BookDownloadAdapter.BookDownHolder, String>();

    private HashMap<String, TxtDownload> mCacheListMap = new HashMap<String, TxtDownload>();

    @Override
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = newConvertView();
        }
        bindView(position, convertView);
        return convertView;
    }

    private View newConvertView() {
        LayoutInflater inflater =
                (LayoutInflater) ShuqiApplication.getContext().getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);

        View view = inflater.inflate(R.layout.item_book_download, null, false);

        final BookDownHolder holder = new BookDownHolder(view);

        view.setTag(holder);

        return view;
    }

    private void bindView(int position, View convertView) {
        TxtDownload info = mList.get(position);
        final BookDownHolder holder = (BookDownHolder) convertView.getTag();
        addUIMap(holder, info.getDownKey());

        holder.bookNameTextView.setText(info.getBookName());
        showSize(info.getFileTotalSize(), holder.bookSizeTextView);
        showTime(info.getCreateTime(), holder.bookDownTimeTextView);
        initCircleProgressBar(info.getDownloadStatus(), info.getFileDownloadSize(),
                info.getFileTotalSize(), holder);
    }

    private void showSize(long totalSize, TextView tv) {
        float size = (float) (totalSize * 0.001 * 0.001);
        float showSize = (float) (Math.round(size * 100)) / 100;
        tv.setText(showSize + " M");
    }

    private void showTime(long time, TextView tv) {
        mDate.setTime(time);
        tv.setText(mDateFormat.format(mDate));
    }

    // 更改单个book状态的UI
    public void updateBookStateUI(String bookDownKey, int state, long loadSize, long totalSize) {
        if (mCacheUIMap != null && mCacheUIMap.containsValue(bookDownKey)
                && mCacheListMap.containsKey(bookDownKey)) {
            TxtDownload info = mCacheListMap.get(bookDownKey);
            info.setDownloadStatus(state);
            info.setFileDownloadSize(loadSize);
            info.setFileTotalSize(totalSize);
            Iterator<Entry<BookDownHolder, String>> it = mCacheUIMap.entrySet().iterator();
            while (it.hasNext()) {
                Entry<BookDownHolder, String> entry = (Entry<BookDownHolder, String>) it.next();
                if (entry.getValue().equals(bookDownKey)) {
                    initCircleProgressBar(state, loadSize, totalSize, entry.getKey());
                    break;
                }
            }
        }
    }

    private float getPercent(long loadSize, long totalSize) {
        if (totalSize > 0) {
            float percent = Float.valueOf(loadSize) / totalSize;
            Log4an.e("mine", "下载进度：" + percent + ";未处理时的下载大小：" + loadSize + "；总大小：" + totalSize);
            return percent;
        }
        return 0;
    }

    private void initCircleProgressBar(int state, long loadSize, long totalSize,
            BookDownHolder holder) {
        if (totalSize > 0) {
            showSize(totalSize, holder.bookSizeTextView);
        }
        int color = R.color.book_paint_bg;
        holder.bookDownProgressbar.setPaintBgColor(color);
        int progress = 0;
        switch (state) {
            case DownConstant.STATE_READY:
            case DownConstant.STATE_DOWNLOADING: {
                float percent = getPercent(loadSize, totalSize);
                progress = (int) (percent * 100);
                Log4an.e("down", "处理后的进度：" + progress);
                if (progress > 99) { // 为了智能断章完成后才显示100%的进度 添加的该段代码
                    progress = 99;
                }
                String text = progress + "%";
                if (state == DownConstant.STATE_READY) {
                    // ready
                    holder.bookStateIconImg.setImageResource(R.drawable.book_down_icon);
                    holder.bookDownProgressbar.setProgress(0);
                    text = "等待";
                } else {
                    // down
                    color = R.color.book_paint_blue;
                    holder.bookDownProgressbar.setPaintColor(color);
                    holder.bookDownProgressbar.setProgressBySize(progress);
                    holder.bookStateIconImg.setImageResource(R.drawable.book_down_icon);
                }
                holder.bookTapTextView.setText(text);
            }
                break;
            case DownConstant.STATE_FINISH:
                holder.bookStateIconImg.setImageResource(R.drawable.book_down_read_nomal);
                color = R.color.book_paint_green;
                holder.bookDownProgressbar.setPaintColor(color);
                holder.bookDownProgressbar.setProgress(100);
                holder.bookTapTextView.setText("打开");
                break;
            case DownConstant.STATE_ERROR: {
                float percent = getPercent(loadSize, totalSize);;
                progress = (int) (percent * 100);
                holder.bookStateIconImg.setImageResource(R.drawable.book_down_error_normal);
                color = R.color.book_paint_red;
                holder.bookDownProgressbar.setPaintColor(color);
                holder.bookDownProgressbar.setProgressBySize(progress);
                holder.bookTapTextView.setText("继续");
            }
                break;
            default:
                break;
        }
    }

    public void setData(List<TxtDownload> list) {
        this.mList = list;
        buildCacheListMap();
        if (mCacheUIMap != null) {
            mCacheUIMap.clear();
        }
        this.notifyDataSetChanged();
    }

    public void buildCacheListMap() {
        if (mCacheListMap != null) {
            mCacheListMap.clear();
            if (mList != null) {
                for (TxtDownload info : mList) {
                    mCacheListMap.put(info.getDownKey(), info);
                }
            }
        }
    }

    // 构建UI map
    private void addUIMap(BookDownHolder holder, String uid) {
        if (mCacheUIMap == null) {
            return;
        }
        mCacheUIMap.put(holder, uid);
    }

    public void onDestroy() {
        if (mCacheUIMap != null) {
            mCacheUIMap.clear();
            mCacheUIMap = null;
        }
        if (mCacheListMap != null) {
            mCacheListMap.clear();
            mCacheListMap = null;
        }
    }

    public static class BookDownHolder {

        public BookDownHolder(View view) {
            rootView = view.findViewById(R.id.item_book_down_root_view);
            bookNameTextView = (TextView) view.findViewById(R.id.item_book_down_name);
            bookSizeTextView = (TextView) view.findViewById(R.id.item_book_down_size);
            bookDownTimeTextView = (TextView) view.findViewById(R.id.item_book_down_time);
            bookTapTextView = (TextView) view.findViewById(R.id.item_book_down_tap);
            bookDownProgressbar =
                    (CircleProgressBarView) view
                            .findViewById(R.id.item_book_down_circleProgressbar);
            bookStateIconImg = (ImageView) view.findViewById(R.id.item_book_down_state_icon);
        }

        public View rootView;

        public TextView bookNameTextView;

        public TextView bookSizeTextView;

        public TextView bookDownTimeTextView;

        public CircleProgressBarView bookDownProgressbar;

        public ImageView bookStateIconImg;

        public TextView bookTapTextView;

    }

}
